package com.ttbj.product.refund.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.RefundDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.refund.RefundService;
import com.ttbj.api.yitong.YtPayService;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.core.util.DateUtil;
import com.ttbj.core.util.DateUtils;
import com.ttbj.refund.dao.RefundMapper;
import com.ttbj.ytpay.dao.YtPayMapper;



@Service("refundService")
public class RefundServiceImpl implements RefundService{
	
	@Autowired
	private RefundMapper refundMapper;
	@Autowired
	private YtPayMapper ytPayMapper;
	@Autowired
	private YtPayService ytPayService;
	
	private static final Logger logger = LoggerFactory.getLogger(RefundServiceImpl.class);
	
	private static final String REFUND_SUCCESS = "0000";	//退款成功
	private static final String REFUND_FAILED = "9999";	//退款失败

	@Override
	public List<RefundDto> findRefundInfoByPage(RefundDto refundDto, Page page) throws BusinessException {
		if (null == refundDto) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		List<RefundDto> refundDtos = this.refundMapper.queryRefundInfoByPage(refundDto, page);
		return refundDtos;
	}

	@Override
	public int findRefundInfoByPageCount(RefundDto refundDto) throws BusinessException {
		if (null == refundDto) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		int count = this.refundMapper.queryRefundInfoByPageCount(refundDto);
		return count;
	}
	
	@Override
	public void refundTransaction(String orgMerOrderNum, String refundAmtStr) throws BusinessException {
		//如果参数为空或者refundAmtStr不为数字
		if (StringUtils.isBlank(orgMerOrderNum) || StringUtils.isBlank(refundAmtStr) || !StringUtils.isNumeric(refundAmtStr)) {
			throw new BusinessException("参数有误！", PlatFormErrorCode.PARAM_IS_NULL.code());
		}
		//查询当前时间所在当天的交易总金额
		Integer dayPaymentAmtSum = this.ytPayMapper.queryTranAmtSumByNowTime();
		logger.info("本天的交易总金额为：{}", dayPaymentAmtSum);
		//如果查询出当天的交易总金额为null或0
		if (null == dayPaymentAmtSum || dayPaymentAmtSum == 0) {
			throw new BusinessException("退款失败！", PlatFormErrorCode.DATA_SECURITY.code());
		}
		//如果退款金额大于本天的交易总金额，则提示不能退款
		if (Integer.parseInt(refundAmtStr) > dayPaymentAmtSum) {
			throw new BusinessException("退款金额大于本天交易总额，不能退款！", PlatFormErrorCode.DATA_SECURITY.code());
		}
		//从数据库中获取支付时间
		String paymentTime = this.ytPayMapper.queryPaymentTimeByMerOrderNum(orgMerOrderNum);
		if (StringUtils.isBlank(paymentTime)) {	//如果返回的时间为null或空，则没有此编号
			throw new BusinessException("无此订单号！", PlatFormErrorCode.DATA_SECURITY.code());
		}
		//获取90天后的Date对象
		Date after90Date = DateUtil.getNextNDate(DateUtils.getSimpleDateTime(paymentTime), 90);
		//支付时间后90天的字符串时间格式
		String paymentTime90After = DateUtils.getDateLongTimePlusStr(after90Date);
		logger.info("支付后90天的时间是：{}", paymentTime90After);
		//比较支付后90天的时间和当前时间前后
		boolean flag = DateUtil.compareDates(DateUtils.getDateLongTimePlusStr(new Date()),paymentTime90After);
		if (flag) {	//如果当前时间大于支付90天后时间，则不能退款
			logger.info("支付后90天的时间大于当前时间退款失败");
			throw new BusinessException("已超过90天，退款失败！", PlatFormErrorCode.DATA_SECURITY.code());
		}else {	//否则可以退款
			logger.info("支付后90天的时间小于当前时间可以退款");
			Map<String, String> map = null;
			try {
				//易通退款操作
				map = this.ytPayService.tkTransaction(orgMerOrderNum, refundAmtStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (map == null) {
				throw new BusinessException("请求退款出现异常", PlatFormErrorCode.DATA_SECURITY.code());
			}
			if (map.get("respCode").equals(REFUND_SUCCESS)) {	//返回0000，退款成功，保存退款记录信息
				map.put("insTime", DateUtils.getDateLongTimePlusStr(new Date()));	//把目前时间放入数据库
				int i = this.refundMapper.inserRefundInfo(map);
			}else{
				//返回其他，则退款失败，返回描述
				throw new BusinessException(map.get("msg"), PlatFormErrorCode.DATA_SECURITY.code());
			}
		}
	}

	@Override
	public int addRefundInfo(Map<String, String> refundMap) throws BusinessException {
		if (refundMap.isEmpty()) {	//如果map中没有键值，则返回true
			throw new BusinessException("数据为空！", PlatFormErrorCode.PARAM_IS_NULL.code());
		}
		int num = this.refundMapper.inserRefundInfo(refundMap);
		return num;
	}
}
